package com.winit.deploy.task.androidTask;

import com.winit.common.util.ShellRunUtil;
import com.winit.core.task.Task;
import com.winit.deploy.bean.WinitAndroidInfo;
import com.winit.deploy.server.WinitJumpServer;
import com.winit.deploy.server.WinitAndroidServer;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 安卓准备过程
 * Created by wangjian on 16/10/17.
 */
public class AndroidPrepareTask extends Task {

    private static Logger logger = LoggerFactory.getLogger(AndroidPrepareTask.class);

    /**
     * 跳板机
     * 用于推送发布包
     */
    private WinitJumpServer jumpServer = null;
    /**
     * 远程终端机,用于校验发布包是否推送成功
     */
    private WinitAndroidServer server;
    /**
     * 必传
     */
    private WinitAndroidInfo androidInfo;

    /**
     * beetle本机发布
     *
     * @param taskId
     * @param expireTime
     * @param androidInfo
     * @param server
     */
    public AndroidPrepareTask(String taskId, Integer expireTime, WinitAndroidInfo androidInfo, WinitAndroidServer server) {
        super(taskId, expireTime);
        this.androidInfo = androidInfo;
        this.server = server;
    }

    /**
     * 跳板机发布
     *
     * @param taskId
     * @param expireTime
     * @param androidInfo
     * @param server
     * @param jumpServer
     */
    public AndroidPrepareTask(String taskId, Integer expireTime, WinitAndroidInfo androidInfo, WinitAndroidServer server
            , WinitJumpServer jumpServer) {
        super(taskId, expireTime);
        this.androidInfo = androidInfo;
        this.server = server;
        this.jumpServer = jumpServer;
    }

    @Override
    public TaskStatus call() throws Exception {
        logger.info("com.winit.deploy.task.androidTask.AndroidPrepareTask#call start taskId=" + this.taskId);
        StringBuffer errorStr = new StringBuffer();

        String dirPath = this.androidInfo.getProjectDirPath();
        String dirName = this.androidInfo.getProjectDirName();
        String serverIp = this.androidInfo.getServerIp();
        String zipTempDir = this.androidInfo.getZipTempDir();
        String packageName = this.androidInfo.getPackageName();

        //2.校验硬盘是否存在空间
        try {
            String percent = this.server.getPercentOfSpace();
            if ("100".equals(percent)) {
                errorStr.append("<br>终端空间已满,请先清理后再进行发布!");
            }
        } catch (Exception e) {
            errorStr.append("<br>检验终端空间剩余,").append(e.getMessage());
        }
        //3.校验发布包临时目录是否存在
        try {
            this.server.isPathExist(zipTempDir, true, true);
        } catch (Exception e) {
            errorStr.append("<br>校验发布包临时存放目录,").append(e.getMessage());
        }
        //4.检验工程发布的目录是否存在
        try {
            this.server.isPathExist(dirPath + "/" + dirName, true, true);
        } catch (Exception e) {
            errorStr.append("<br>校验工程发布目录,").append(e.getMessage());
        }
        //6.检验工程备份目录是否存在
        if (!this.androidInfo.isVmEnv()) {
            try {
                this.server.isPathExist(dirPath, true, true);
            } catch (Exception e) {
                errorStr.append("<br>校验工程备份目录,").append(e.getMessage());
            }
        }
        if (!StringUtils.isEmpty(errorStr.toString())) {
            throw new Exception(errorStr.toString());
        }

        try {
            if (this.jumpServer != null) {
                String fromPath = ProjectUtil.getEditionPath(this.androidInfo.getProjectName(),this.androidInfo.getEditionNum())+"target/"+this.androidInfo.getPackageName()+".zip";
                //推送war包至终端机
                this.jumpServer.doPush(fromPath, zipTempDir + "/" + packageName + ".zip", serverIp, this.androidInfo.getSshPort());
            } else {
                this.doPush();
            }
            this.server.doCheckPackage();

        } catch (Exception e) {
            throw e;
        } finally {
        }

        logger.info("com.winit.deploy.task.androidTask.AndroidPrepareTask#call end taskId=" + this.taskId);
        return TaskStatus.STATUS_SUCCESS;
    }

    /**
     * 从beetle本机推送
     *
     * @return
     * @throws Exception
     */
    private void doPush() throws Exception {
        String fromPath = ProjectUtil.getEditionPath(this.androidInfo.getProjectName(),this.androidInfo.getEditionNum())+"target/"+this.androidInfo.getPackageName()+".zip";
        String[] param = new String[7];
        param[0] = "scp";
        param[1] = "-i";
        param[2] = this.androidInfo.getKeyFilePath();
        param[3] = "-P";
        param[4] = this.androidInfo.getSshPort();
        param[5] = fromPath;
        param[6] = this.androidInfo.getUserName() + "@" + this.androidInfo.getServerIp() + ":"
                + this.androidInfo.getZipTempDir() + "/" + this.androidInfo.getPackageName() + ".zip";
        String rtnStr = ShellRunUtil.runShell(param);
        logger.info("AndroidPrepareTask:从beetle本机推送发布包,返回:" + rtnStr);
        if (!StringUtils.isEmpty(rtnStr)) {
            throw new Exception("AndroidPrepareTask:从beetle本机推送发布包失败," + rtnStr);
        }
    }
}
